package com.honghea.rxhttp;

import android.util.Log;

import com.honghea.rxhttp.factory.IOkHttpClientFactory;
import com.honghea.rxhttp.factory.IRetrofitFactory;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

public class HttpService {

    private final static String TAG = "HttpService";

    private final OkHttpClient client;
    private String retrofit_code;
    private Retrofit retrofit;

    private static volatile HttpService mInstance;

    private HttpService(IOkHttpClientFactory factory) {
        client = factory.provide();
    }

    public static void init(IOkHttpClientFactory factory) {
        if (mInstance != null) {
            throw new RuntimeException("HttpService has been initialized");
        }
        mInstance = new HttpService(factory);
    }

    public static HttpService newService(IRetrofitFactory factory, String BASE_URL, String tag) {
        if (mInstance == null) {
            throw new NullPointerException("HttpService has not been initialized");
        }
        mInstance.retrofit = factory.provide(mInstance.client, BASE_URL);
        mInstance.retrofit_code = tag;
        return mInstance;
    }

    public <ServiceInterface> ServiceInterface build(Class<ServiceInterface> service) {
        if (mInstance.retrofit == null) {
            throw new NullPointerException("HttpService has not been bind to any Retrofit");
        }
        Log.d(TAG, "HttpService use Retrofit tag: " + mInstance.retrofit_code);
        return mInstance.retrofit.create(service);
    }


    public static void main(String[] args) {

    }
}
